package zl.ordermanager.controller;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import jxl.Sheet;
import jxl.Workbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import zl.ordermanager.service.PurchaseOrderService;
import zl.ordermanager.service.UserService;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.EInvoiceType;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.PurchaseOrder;
import zl.ordermanager.vo.Total;

@Controller
@RequestMapping("/purchaseOrder")
public class PurchaseOrderController extends BaseController {

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private UserService userService;

	@RequestMapping("/showList")
	public String showList(PageHelper pageHelper, Model model) {
		Total total = new Total();
		DataGrid<PurchaseOrder> dataGrid = purchaseOrderService.dataGrid(pageHelper, total);
		List<PurchaseOrder> purchaseOrderList = dataGrid.getList();
		long totalCount = dataGrid.getTotal();

		model.addAttribute("purchaseOrderList", purchaseOrderList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageHelper", pageHelper);
		model.addAttribute("total", total);
		model.addAttribute("invoiceTypeList", EInvoiceType.values());

		return "purchaseOrderList";
	}

	@RequestMapping("/showAdd")
	public String showAdd(Model model) {

		model.addAttribute("invoiceTypeList", EInvoiceType.values());

		return "purchaseOrderAdd";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(PurchaseOrder purchaseOrder) {
		try {
			purchaseOrderService.add(purchaseOrder);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/showEdit/{orderId}")
	public String showEdit(@PathVariable("orderId") Integer orderId, Model model) {
		PurchaseOrder purchaseOrder = purchaseOrderService.get(orderId);

		model.addAttribute("purchaseOrder", purchaseOrder);
		model.addAttribute("invoiceTypeList", EInvoiceType.values());

		return "purchaseOrderEdit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView edit(PurchaseOrder purchaseOrder) {
		try {
			purchaseOrderService.edit(purchaseOrder);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}
		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/delete/{orderId}")
	public ModelAndView delete(@PathVariable("orderId") Integer orderId) {

		purchaseOrderService.delete(orderId);

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/upload")
	public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {

		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		// String fileName = new Date().getTime()+".jpg";
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		try {
			importExcel(targetFile);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		} finally {
			targetFile.delete();
		}

		return ajaxDoneSuccess("导入成功");
	}

	private void importExcel(File file) throws Exception {
		if (!file.getName().substring(file.getName().length() - 3).equals("xls")) {
			throw new Exception("文件不是Excel文件！");
		}

		Workbook workbook = Workbook.getWorkbook(file);
		Sheet sheet = workbook.getSheet(0);
		if (sheet.getCell(0, 0).getContents().equals("单据编号") && sheet.getCell(1, 0).getContents().equals("日期")
				&& sheet.getCell(2, 0).getContents().equals("单位全名") && sheet.getCell(3, 0).getContents().equals("部门全名")
				&& sheet.getCell(4, 0).getContents().equals("附加说明") && sheet.getCell(5, 0).getContents().equals("金额")) {
			int row = 1;
			while (row < sheet.getRows()) {
				String orderNo = sheet.getCell(0, row).getContents();
				String orderDate = sheet.getCell(1, row).getContents();
				String company = sheet.getCell(2, row).getContents();
				String orderType = sheet.getCell(3, row).getContents();
				String ai = sheet.getCell(4, row).getContents();
				String money = sheet.getCell(5, row).getContents();

				if (orderNo == null || orderNo.isEmpty()) {
					continue;
				}
				PurchaseOrder findPurchaseOrder = purchaseOrderService.getByOrderNo(orderNo);
				if (findPurchaseOrder == null) {
					PurchaseOrder purchaseOrder = new PurchaseOrder();
					purchaseOrder.setOrderNo(orderNo);
					purchaseOrder.setOrderDate(orderDate);
					purchaseOrder.setCompany(company);
					purchaseOrder.setOrderType(orderType);
					purchaseOrder.setAi(ai);
					purchaseOrder.setMoney(money);

					purchaseOrderService.add(purchaseOrder);
				} else {
					findPurchaseOrder.setOrderDate(orderDate);
					findPurchaseOrder.setCompany(company);
					findPurchaseOrder.setOrderType(orderType);
					findPurchaseOrder.setAi(ai);
					findPurchaseOrder.setMoney(money);

					purchaseOrderService.edit(findPurchaseOrder);
				}

				row++;
			}
		} else {
			throw new Exception("Excel文件格式错误");
		}
	}
}
